package ru.evga.gwt.lib.common.client.place;

import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceTokenizer;
import com.google.gwt.place.shared.Prefix;

public class PlaceImpl extends Place
{
    public static final String TOKEN_SEPARATOR = "!";
    public static final String TOKEN_PAIR_SEPARATOR = "&";

    /**
     * Tokenizer.
     */
    @Prefix("place")
    public static class Tokenizer implements PlaceTokenizer<PlaceImpl>
    {

        public PlaceImpl getPlace(String token)
        {
            return new PlaceImpl(token);
        }

        public String getToken(PlaceImpl place)
        {
            return place.getToken();
        }
    }
    
    public static class PlaceImplBuilder
    {
        private StringBuilder m_stringBuilder; 
        
        public PlaceImplBuilder()
        {
            m_stringBuilder = new StringBuilder();
        }
        
        public PlaceImpl build()
        {
            return new PlaceImpl(m_stringBuilder.toString());
        }
        
        public PlaceImplBuilder add(String key, String value)
        {
            if(m_stringBuilder.length() > 0)
            {
                m_stringBuilder.append(TOKEN_SEPARATOR);
            }
            m_stringBuilder.append(key);
            if(value != null && value.length() > 0)
            {
                m_stringBuilder.append(TOKEN_PAIR_SEPARATOR).append(value);
            }
            return this;
        }
    }

    private final String m_strToken;

    public PlaceImpl(String token)
    {
        m_strToken = token;
    }
    
    public String getToken()
    {
        return m_strToken;
    }

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj)
        {
            return true;
        }
        if (obj == null)
        {
            return false;
        }
        if (getClass() != obj.getClass())
        {
            return false;
        }
        PlaceImpl other = (PlaceImpl) obj;
        if (m_strToken != other.m_strToken)
        {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((m_strToken == null) ? 0 : m_strToken.hashCode());
        return result;
    }

    @Override
    public String toString()
    {
        return "MenuPlace [" + getToken() + "]";
    }
}
